// pages/soldItems/soldItems.js
Page({
    data: {
        currentTab: 0, // 当前选中的标签索引
        statusTitles: ['待付款', '待发货', '待收货', '已完成'],
        statusValues: [1, 2, 3, 4], // 对应订单状态值
        orderList: [
            [],
            [],
            [],
            []
        ], // 按状态分类的订单列表
        isLoading: [true, true, true, true], // 各状态加载状态
        hasMore: [true, true, true, true], // 各状态是否有更多数据
        pageNum: [1, 1, 1, 1], // 各状态当前页码
        pageSize: 10, // 每页显示数量
        userId: '', // 当前用户ID
        showShipModal: false, // 发货表单弹窗显示状态
        shipMethod: '', // 选择的发货方式
        expressCompany: '', // 快递公司
        expressNumber: '', // 快递单号
        currentOrderId: '' // 当前处理的订单ID
    },

    onLoad(options) {
        // 获取当前用户ID
        const userInfo = wx.getStorageSync('userInfo');
        if (!userInfo) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            wx.navigateTo({
                url: '/pages/login/login'
            });
            return;
        }

        this.setData({
            userId: userInfo._id
        });

        // 加载各状态订单
        this.loadOrderList(0);
    },
    // 切换标签
    switchTab(e) {
        console.log(e);
        const index = e.currentTarget.dataset.index;
        this.setData({
            currentTab: Number(index)
        });
        this.setData({
            pageNum: [1, 1, 1, 1],
            orderList: [
                [],
                [],
                [],
                []
            ],
            hasMore: [true, true, true, true]
        });
        console.log(index);
        this.loadOrderList(index);
    },

    // 加载订单列表
    async loadOrderList(tabIndex) {
        try {
            this.setData({
                isLoading: this.data.isLoading.map((item, i) => i == tabIndex ? true : item)
            });

            const {
                userId,
                pageNum,
                pageSize,
                statusValues
            } = this.data;
            const status = statusValues[tabIndex];
            console.log(status);
            // 调用云函数获取订单列表
            const res = await wx.cloud.callFunction({
                name: 'queryOrdersList',
                data: {
                    type: 'sell', // 卖出的订单
                    userId: userId,
                    // userId: '0253ee36683566070042b1cc538e95f0',
                    status: status,
                    pageNum: pageNum[tabIndex],
                    pageSize: pageSize
                }
            });
            console.log(res);
            if (res.result.success) {
                res.result.orders.forEach(item => {
                    if (item.goodsInfo.goodsImage) {
                        let arr = item.goodsInfo.goodsImage.split(',')
                        item.Image = arr
                    }
                })
                const newOrderList = [...this.data.orderList[tabIndex], ...res.result.orders];
                const hasMore = res.result.orders.length >= pageSize;

                this.setData({
                    orderList: this.data.orderList.map((item, i) => i == tabIndex ? newOrderList : item),
                    hasMore: this.data.hasMore.map((item, i) => i == tabIndex ? hasMore : item),
                    pageNum: this.data.pageNum.map((item, i) => i == tabIndex ? item + 1 : item),
                    isLoading: this.data.isLoading.map((item, i) => i == tabIndex ? false : item)
                });
                console.log(this.data);
            } else {
                wx.showToast({
                    title: res.result.message || '加载失败',
                    icon: 'none'
                });
            }
        } catch (error) {
            console.error('加载订单失败:', error);
            wx.showToast({
                title: '系统错误，请重试',
                icon: 'none'
            });
            this.setData({
                isLoading: this.data.isLoading.map((item, i) => i == this.data.currentTab ? false : item)
            });
        }
    },

    // 下拉刷新
    onPullDownRefresh() {
        this.setData({
            pageNum: [1, 1, 1, 1],
            orderList: [
                [],
                [],
                [],
                []
            ],
            hasMore: [true, true, true, true]
        });

        this.loadOrderList(this.data.currentTab);
        wx.stopPullDownRefresh();
    },

    // 上拉加载更多
    onReachBottom() {
        if (this.data.hasMore[this.data.currentTab]) {
            this.loadOrderList(this.data.currentTab);
        }
    },

    // 查看订单详情
    viewOrderDetail(e) {
        const orderId = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/orderDetail/orderDetail?orderId=${orderId}`
        });
    },

    // 发货操作
    handleShipOrder(e) {
        console.log(e);
        const orderId = e.currentTarget.dataset.id;
        this.setData({
            showShipModal: true,
            currentOrderId: orderId,
            shipMethod: '',
            expressCompany: '',
            expressNumber: ''
        });
        // wx.showModal({
        //     title: '确认发货',
        //     content: '是否确认已发货？',
        //     success: (res) => {
        //         if (res.confirm) {
        //             this.updateOrderStatus(orderId, 3); // 更新为已发货状态
        //         }
        //     }
        // });
    },
    // 选择发货方式
    selectShipMethod: function (e) {
        const method = e.currentTarget.dataset.method;
        this.setData({
            shipMethod: method
        });
    },

    // 快递公司输入
    onExpressCompanyInput: function (e) {
        this.setData({
            expressCompany: e.detail.value
        });
    },

    // 快递单号输入
    onExpressNumberInput: function (e) {
        this.setData({
            expressNumber: e.detail.value
        });
    },

    // 关闭发货表单
    closeShipModal: function () {
        this.setData({
            showShipModal: false
        });
    },

    // 确认发货
    confirmShipOrder: function () {
        const {
            currentOrderId,
            shipMethod,
            expressCompany,
            expressNumber
        } = this.data;

        // 验证输入
        if (!shipMethod) {
            wx.showToast({
                title: '请选择发货方式',
                icon: 'none'
            });
            return;
        }

        if (shipMethod === 'express' && (!expressCompany || !expressNumber)) {
            wx.showToast({
                title: '请填写快递公司和快递单号',
                icon: 'none'
            });
            return;
        }

        // 显示加载状态
        wx.showLoading({
            title: '发货中...',
        });
        // 调用云函数
        wx.cloud.callFunction({
            name: 'shipOrder',
            data: {
                orderId: currentOrderId,
                shipMethod: shipMethod,
                expressCompany: expressCompany,
                expressNumber: expressNumber,
                operatorId: wx.getStorageSync('userInfo')._id,
                operatorName: wx.getStorageSync('userInfo').nickName 
            }
        }).then(res => {
            wx.hideLoading();

            if (res.result.success) {
                wx.showToast({
                    title: '发货成功',
                    icon: 'success'
                });
                this.closeShipModal();
                // 刷新订单列表
                this.loadOrderList(this.data.currentTab);
            } else {
                wx.showToast({
                    title: res.result.message || '发货失败',
                    icon: 'none'
                });
                console.error('发货失败', res.result.error);
            }
        }).catch(err => {
            wx.hideLoading();
            wx.showToast({
                title: '网络错误，请重试',
                icon: 'none'
            });
            console.error('调用云函数失败', err);
        });
    },
    // 更新订单状态
    async updateOrderStatus(orderId, newStatus) {
        try {
            wx.showLoading({
                title: '处理中...'
            });

            await wx.cloud.callFunction({
                name: 'updateOrderStatus',
                data: {
                    orderId: orderId,
                    newStatus: newStatus,
                }
            }).then(res => {
                console.log(res);
                if (res.result.success) {
                    wx.hideLoading();
                    wx.showToast({
                        title: '操作成功',
                        icon: 'success'
                    });
                    this.setData({
                        pageNum: [1, 1, 1, 1],
                        orderList: [
                            [],
                            [],
                            [],
                            []
                        ],
                        hasMore: [true, true, true, true]
                    });
                    // 刷新当前状态订单列表
                    this.loadOrderList(this.data.currentTab);
                } else {
                    wx.showToast({
                        title: res.result.message || '加载失败',
                        icon: 'none'
                    });
                }
            });


        } catch (error) {
            wx.hideLoading();
            console.error('更新订单状态失败:', error);
            wx.showToast({
                title: '操作失败',
                icon: 'none'
            });
        }
    }
});